angular.module('U9ImHd.utility')

.factory('Device', ['$rootScope', '$q', '$ionicPlatform', '$cordovaDevice', 'ConnectService', 'Http', 'APPCONSTANTS',
    function($rootScope, $q, $ionicPlatform, $cordovaDevice, ConnectService, Http, APPCONSTANTS) {
        var deviceDefer = $q.defer(),
            _registerInfo = {},
            o = {
                loaded: deviceDefer.promise
            };

        o.getUUID = function () {
            return window.cordova ? $cordovaDevice.getUUID() : APPCONSTANTS.debugDeviceUUID;
        };
        o.getIpAddress = function () {
            var defer = $q.defer();
            
            if (window.cordova && cordova.plugins.Network) {
                cordova.plugins.Network.getIpAddress(function (ip) {
                    defer.resolve(ip);
                });
            } else {
                defer.reject();
            }

            return defer.promise;
        };
        o.getMacAddress = function () {
            var defer = $q.defer();

            if (window.cordova && cordova.plugins.Network) {
                cordova.plugins.Network.getMacAddress(function (mac) {
                    defer.resolve(mac);
                });
            } else {
                defer.reject();
            }

            return defer.promise;
        };
        o.updateLastRegister = function () {
            var defer = $q.defer();

            Http.post({
                url: APPCONSTANTS.getLastRegisterURL,
                data: {
                    Parameter: {
                        TerminalUniqueID: o.getUUID()
                    }
                },
                ignoreErrorHandler: true
            }).then(function (registerInfo) {
                _registerInfo = registerInfo;
                defer.resolve(registerInfo);
            }, function (err) {
                _registerInfo = {};
                defer.reject(err);
            });

            return defer.promise;
        };
        o.get = function (key) {
            return key ? _registerInfo[key] : angular.copy(_registerInfo);
        };

        $ionicPlatform.ready(function () {
            ConnectService.loaded.then(function () {
                o.updateLastRegister().finally(function () {
                    deviceDefer.resolve();
                });
            });
        });

        return o;
    }
]);
